package com.jzo2o.foundations.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.model.Result;
import com.jzo2o.foundations.constants.RedisConstants;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.*;
import com.jzo2o.foundations.service.IServeRegionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ServeRegionServiceImpl  extends ServiceImpl<ServeMapper, Serve> implements IServeRegionService  {
    @Autowired
    private  ServeMapper serveMapper;
    @Autowired
    private  IServeRegionService serveRegionService;
    @Autowired
    private  RegionMapper regionMapper;

    private static final Integer ONE = 1;
    private static final Integer ZONE = 0;
    private static final Integer TWO = 2;

    /**
     * 分页查询区域服务详情
     * @param reqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> pageResult(ServePageQueryReqDTO reqDTO) {
        Page<ServeResDTO> page = new Page<>(reqDTO.getPageNo(), reqDTO.getPageSize());
        List<ServeResDTO> list = serveMapper.pageServeByRegionId(page,reqDTO.getRegionId());
        return PageResult.of(list,reqDTO.getPageSize().intValue(), page.getPages(), page.getTotal());
    }

    /**
     * 新增区域服务项
     * @param reqDTOS
     * @return
     */
    @Override
    public void addServeRegion(List<ServeUpsertReqDTO> reqDTOS) {
        List<Serve> serveList = new ArrayList<>();
        for (ServeUpsertReqDTO reqDTO : reqDTOS) {
            Serve serve = new Serve();
            serve.setRegionId(reqDTO.getRegionId());
            serve.setServeItemId(reqDTO.getServeItemId());
            Region region = regionMapper.selectById(reqDTO.getRegionId());
            String cityCode = region.getCityCode();
            serve.setCityCode(cityCode);
            serve.setSaleStatus(0);
            serve.setPrice(reqDTO.getPrice());
            serve.setCreateTime(LocalDateTime.now());
            serve.setUpdateTime(LocalDateTime.now());
            serveList.add(serve);
        }
        serveRegionService.saveBatch(serveList);
    }

    /**
     * 删除区域内某服务项，根据服务项id
     * @param id
     */
    @Override
    public void deleteById(String id) {
        serveMapper.deleteById(id);
    }

    /**
     * 根据id更新价格
     * @param id 服务ID
     * @param price 新价格
     */
    @Override
    public void updatePriceById(String id, BigDecimal price) {
        if (!StringUtils.hasText(id) || price==null){
            throw new RuntimeException("删除失败，参数传递异常");
        }
        Serve serve = serveMapper.selectById(id);
        serve.setPrice(price);
        LambdaQueryWrapper<Serve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Serve::getId,id);
        serveMapper.update(serve,queryWrapper);
    }

    /**
     * 上架
     * @param id
     */
    @Override
    @Cacheable(value = "JZ_CACHE:SERVE_RECORD",key = "#p0")
    public void onSale(String id) {
        Serve serve = serveMapper.selectById(id);
        serve.setSaleStatus(TWO);
        LambdaQueryWrapper<Serve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Serve::getId,id);
        serveMapper.update(serve,queryWrapper);
    }

    /**
     * 下架
     * @param id
     */
    @Override
    @CacheEvict(value = "JZ_CACHE:SERVE_RECORD",key = "#p0")
    public void offSale(String id) {
        Serve serve = serveMapper.selectById(id);
        serve.setSaleStatus(ONE);
        LambdaQueryWrapper<Serve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Serve::getId,id);
        serveMapper.update(serve,queryWrapper);
    }

    /**
     * 设置热门
     * @param id
     */
    @Override
    @Cacheable(value = RedisConstants.CacheName.HOT_SERVE,key = "#p0")
    public void onHot(String id) {
        Serve serve = serveMapper.selectById(id);
        serve.setIsHot(ONE);
        LambdaQueryWrapper<Serve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Serve::getId,id);
        serveMapper.update(serve,queryWrapper);
    }

    /**
     * 取消热门
     * @param id
     */
    @Override
    @CacheEvict(value = RedisConstants.CacheName.HOT_SERVE,key = "#p0" )
    public void offHot(String id) {
        Serve serve = serveMapper.selectById(id);
        serve.setIsHot(ZONE);
        LambdaQueryWrapper<Serve> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Serve::getId,id);
        serveMapper.update(serve,queryWrapper);
    }

    /**
     * 根据区域id查询所有服务分类以及服务内容
     * 门户查询
     * 只保留前两个分类、以及分类中前四个服务返回
     * @param regionId
     * @return
     */
    @Override
    @Transactional
    @Cacheable(value = "JZ_CACHE:SERVE_ICON",key = "#p0")
    public List<ServeCategoryResDTO> getServeCategoryList(String regionId) {
        List<ServeCategoryResDTO> serverList = serveMapper.getServeCategoryList(regionId);
        int size = serverList.size() > 2 ? 2 : serverList.size();
        serverList = serverList.stream().limit(size).collect(Collectors.toList());

        for (ServeCategoryResDTO serveCategoryResDTO : serverList) {
            List<ServeSimpleResDTO> serveResDTOList = serveCategoryResDTO.getServeResDTOList();
            int size2 =  serveResDTOList.size() >4 ? 4: serveResDTOList.size();
            serveResDTOList = serveResDTOList.stream().limit(size).collect(Collectors.toList());
            serveCategoryResDTO.setServeResDTOList(serveResDTOList);
        }

        return serverList;
    }

    /**
     * 查询热门服务，只返回排名第一的
     * @param regionId
     * @return
     */
    @Override
    @Cacheable(value = "JZ_CACHE:HOT_SERVE",key = "#p0")
    public List<ServeAggregationSimpleResDTO> getHotServeList(String regionId) {
        List<ServeAggregationSimpleResDTO> hotServeList =  serveMapper.getHotServeList(regionId);
        return hotServeList;

    }

    /**
     *   全部服务类型列表
     * @param regionId
     * @return
     */
    @Override @Cacheable(value = "JZ_CACHE:SERVE_TYPE",key = "#p0")
    public List<ServeAggregationTypeSimpleResDTO> getAllTypeByRegionId(Long regionId) {
        return serveMapper.queryServeTypeByRegionId(regionId);
    }

    /**
     *   查询服务详情
     * @param id
     * @return
     */
    @Override
    public ServeAggregationSimpleResDTO getServeDetailById(Long id) {
        return serveMapper.getServeDetailById(id);
    }

}
